package org.ccay.security.authc;

import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.DefaultHashService;
import org.apache.shiro.crypto.hash.HashRequest;
import org.apache.shiro.util.ByteSource;
import org.ccay.security.entity.User;
import org.springframework.util.Assert;

/**
 * 用户登录凭证加密工具
 * @author chaowangbang
 *
 */
public class UserEncryptUtil {

	/**
	 * 生成密码机盐并转化为 Hex-formatted 字符串设置到给定参数的password及salt属性中
	 * 采用安全随机数算法生成盐，并使用SHA-512进行散列
	 * @param user
	 */
	public static String[] encrypt(String lawPassword){
		Assert.notNull(lawPassword, "password must not be null");
		DefaultHashService hashService = new DefaultHashService(); 
		//默认算法SHA-512
		hashService.setHashAlgorithmName("SHA-512");
		hashService.setGeneratePublicSalt(true);
		String salt = new SecureRandomNumberGenerator().nextBytes().toHex();
		HashRequest request = new HashRequest.Builder().setSource(ByteSource.Util.bytes(lawPassword)).setSalt(salt).build();
		String password = hashService.computeHash(request).toHex();
		return new String[] {password,salt};
	}
}
